package com.baitiaojun.web.core.handler;

import cn.hutool.core.date.DateUtil;
import org.springframework.beans.propertyeditors.StringTrimmerEditor;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.InitBinder;

import java.beans.PropertyEditorSupport;
import java.util.Date;

/**
 * 全局请求参数处理
 */
//ControllerAdvice对所有注解了@RequestMapping的控制器内的方法有效
@ControllerAdvice
public class GlobalRequestParamsHandler {

    @InitBinder
    public void initBinder(WebDataBinder webDataBinder) {
        //字符串参数去前后空格
        webDataBinder.registerCustomEditor(String.class, new StringTrimmerEditor(true));

        //日期参数格式化, 对于字符串参数有效
        webDataBinder.registerCustomEditor(Date.class, new PropertyEditorSupport() {
            @Override
            public void setAsText(String text) throws IllegalArgumentException {
                super.setValue(DateUtil.parse(text));
            }
        });
    }
}
